<template>
    <div class="box">
        <!-- <div class="left">
              <el-menu
                  default-active="AAPL.usa"
                  class="el-menu-vertical-demo"
                  background-color="#191919"
                  text-color="#dee4eb"
                  active-text-color="#ff6900"
                  :unique-opened="true"
                  @select='handleSelect'
                  @open="handleOpen"
                  @close="handleClose">
                  <el-submenu v-for="item in NavMenuAry" :key="item.Title" :index="item.Title">
                  <template slot="title">
                      <i class="el-icon-menu"></i>
                      <span>{{item.Title}}</span>
                  </template>
                      <el-menu-item v-for="subItem in item.Sub" :key='subItem.Code' :index="subItem.Code">{{subItem.Name}}</el-menu-item>
                  </el-submenu>
              </el-menu>
        </div> -->

        <div class="right" ref="right">
            <!-- <div class="rightTab" ref="rightTab">
                    <div class="btn showMinute" :class="{ active: chartType == 'minute' }"
                        @click="changeRightContent('minute')">分时图</div>
                    <div class="btn showKline" :class="{ active: chartType == 'kline' }" @click="changeRightContent('kline')">
                        K线图</div>
            </div>-->
            <div class="rightContent" ref="rightContent">
                <!-- <div class="contentBox" v-show='chartType == "minute"'>
                          <div class="indexWrap" ref="minute_indexWrap">
                              <div class="btnGroup">
                                  <div class="btn" v-for="(indexName) in MinuteIndexMenu" :key="indexName.ID"
                                      @click="changeChartIndex(indexName.ID)">{{ indexName.Name }}</div>
                              </div>
                          </div>
                          <div class="periodWrap" ref='minute_periodWrap'>
                              <div class="btnGroup">
                                  <div class="btn" :class="{ active: MinuteDayIndex == index }"
                                      v-for="(item, index) in MinuteDayMenu" :key="item.ID"
                                      @click="OnClickMinuteDayMenu(index, item)">{{ item.Name }}</div>
                              </div>
                          </div>

                </div>-->

                <div class="contentBox">
                    <!-- 分时 -->
                    <!-- <div class="indexWrap" ref="kline_indexWrap">
                                <div class="btnGroup">
                                    <div class="btn" v-for="(item) in KLineIndexMenu" :key="item.ID"
                                        @click="ChangeKLineIndex(item)">{{ item.Name }}</div>
                                </div>:class="{ active: KLinePeriodIndex == index }"
                    </div>-->
                    <div class="periodWrap kline_periodWrap" ref="kline_periodWrap">
                        <!-- DWM 分 -->
                        <div class="btnGroup" style="position:relative">
                            <div
                                class="btn2"
                                v-for="(item, index) in KLinePeriodMenu"
                                :class="{ active: KLinePeriodIndex == index }"
                                :key="item.ID"
                                @click="index == 0 ? changeRightContent('minute') : OnClickKLinePeriodMenu(index, item, 'kline')"
                            >
                                <span>{{ item.Name }}</span>
                            </div>
                            <div class="btn2" @click="isShow ? isShow = false : isShow = true">
                                <div class="btn2">
                                    <!-- :class="KLinePeriodIndex === index ? 'active' : ''" -->
                                    <img src="../../../assets/img/options.png" alt/>
                                </div>
                            </div>
                            <div style="position:absolute;right: 0;top: 25px;;z-index: 99;" v-if="isShow == true">
                                <div
                                    class="btnGroup"
                                    v-show="IsShowRightMenu"
                                    style="display: flex;flex-direction: column;"
                                >
                                    <div
                                        class="btn"
                                        :class="{ active: KLineRightIndex == index }"
                                        v-for="(item, index) in KLineRightMenu"
                                        :key="item.ID"
                                        style="padding:10px"
                                        @click="OnClickKLineRightMenu(index, item)"
                                    >{{ item.Name }}
                                    </div>
                                    <div
                                        class="btn"
                                        v-for="(item) in KLineIndexMenu"
                                        :key="item.ID"
                                        style="padding:10px"
                                        @click="ChangeKLineIndex(item)"
                                    >{{ item.Name }}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="hqchart" id="hqchart_minute" ref="kline" v-show="chartType == 'minute'"></div>
                    <div class="hqchart" id="hqchart_kline" ref="kline2" v-show="chartType == 'kline'"></div>

                    <!-- <div class="statementWrap" ref="kline_statementWrap">
                                郑重声明：本页面所有数据来自互联网或自动生成的测试数据,仅用于学习HQChart图形库使用,不构成任何投资价值信息。如使用者依据本网站提供的信息、资料及图表进行金融、证券等投资所造成的盈亏与本网站无关。
                    </div>-->
                </div>
            </div>
        </div>

        <!-- <div class="right" ref="kline_right" >

        </div>-->
    </div>
</template>

<script>
import _ from "lodash";
import HQChart from "hqchart";
import "hqchart/src/jscommon/umychart.resource/css/tools.css";
import "hqchart/src/jscommon/umychart.resource/font/iconfont.css";
import EastMoney from "../../../eastmoney/HQData.js";
import i18n from '@/locales/index.js'
//源码调试用
//import Chart from '../jscommon/umychart.vue/umychart.vue.js'
//import '../jscommon/umychart.resource/css/tools.css'
//import '../jscommon/umychart.resource/font/iconfont.css'
//var HQChart={ Chart:Chart };
HQChart.Chart.MARKET_SUFFIX_NAME.GetMarketStatus = function (symbol) {
    return 2;
}; //一直交易
function DefaultData() {
}

DefaultData.GetMinuteOption = function () {
    var option = {
        Type: "分钟走势图", //创建图形类型
        //Type:'分钟走势图横屏',

        //窗口指标
        Windows: [
            // { Index:"KDJ", Modify: false, Change: true, Close: true},
            // { Index: "KDJ", Modify: false, Change: false, Close: false }
        ],

        Symbol: "AAPL.usa",
        IsAutoUpdate: true, //是自动更新数据
        AutoUpdateFrequency: 20000,
        DayCount: 1, //1 最新交易日数据 >1 多日走势图
        IsShowRightMenu: false, //是否显示右键菜单
        CorssCursorTouchEnd: true,

        CorssCursorInfo: {Left: 1, Right: 1},

        MinuteLine: {
            IsDrawAreaPrice: true, //是否画价格面积图
            IsShowAveragePrice: true //不显示均线
        },

        //边框
        Border: {
            Left: 1, //左边间距
            Right: 1, //右边间距
            Top: 0,
            Bottom: 1,
            AutoRight: {Blank: 10, MinWidth: 40},
            AutoLeft: {Blank: 10, MinWidth: 40}
        },

        //子框架设置
        // Height 是否显示成交量 柱状图 0 false
        Frame: [{SplitCount: 5}, {SplitCount: 3, Height: 0}],

        //扩展图形
        ExtendChart: [
            //{Name:'MinuteTooltip' }  //手机端tooltip
        ]
    };

    return option;
};

DefaultData.GetMinuteIndexMenu = function () {
    var data = [
        {Name: "MACD", ID: "MACD", WindowIndex: 2},
        {Name: "KDJ", ID: "KDJ", WindowIndex: 2},
        {Name: "DMI", ID: "DMI", WindowIndex: 2},
        {Name: "ROC", ID: "ROC", WindowIndex: 2}
    ];

    return data;
};

DefaultData.GetKLineIndexMenu = function () {
    var data = [
        {Name: "MA", ID: "MA", WindowIndex: 0},
        {Name: "BOLL", ID: "BOLL", WindowIndex: 0},
        {Name: "MACD", ID: "MACD", WindowIndex: 1},
        {Name: "KDJ", ID: "KDJ", WindowIndex: 1},
        {Name: "DMI", ID: "DMI", WindowIndex: 1},
        {Name: "ROC", ID: "ROC", WindowIndex: 1}
    ];

    return data;
};


DefaultData.GetKLineOption = function () {
    var option = {
        Type: "历史K线图", //创建图形类型
        IsShowCorssCursorInfo: false,
        //窗口指标
        Windows: [
            {Index: "MA", Modify: true, Change: false, height: 20},
            {Index: "ATR", Modify: false, Change: false, Close: false}
            // { Index: "MACD", Modify: true, Change: true, Close: false }
        ],
        Symbol: "600015.sh",
        IsAutoUpdate: true, //是自动更新数据
        AutoUpdateFrequency: 1000,
        IsApiPeriod: true,
        IsShowRightMenu: false, //是否显示右键菜单
        CrossCursorTouchEnd: true,
        //CorssCursorTouchEnd:true,

        KLine: {
            DragMode: 1, //拖拽模式 0 禁止拖拽 1 数据拖拽 2 区间选择
            Right: 0, //复权 0 不复权 1 前复权 2 后复权
            Period: 0, //周期 0 日线 1 周线 2 月线 3 年线
            MaxReqeustDataCount: 1000, //数据个数
            PageSize: 60, //一屏显示多少数据
            KLineDoubleClick: false, //双击分钟走势图
            IsShowTooltip: false, //是否显示K线提示信息
            DrawType: 0,
            RightSpaceCount: 2
        },

        CorssCursorInfo: {Left: 0, Right: 1},

        //标题设置
        KLineTitle: {
            IsShowName: false, //不显示股票名称
            IsShowSettingInfo: false, //不显示周期/复权
            isShowDateTime: false
        },

        //边框
        Border: {
            Left: 1, //左边间距
            Right: 1, //右边间距
            Top: 0,
            Bottom: 15,
            AutoRight: {Blank: 10, MinWidth: 40}
        },

        //子框架设置
        Frame: [
            {
                SplitCount: 5,
                IsShowLeftText: false,
                IsShowYLine: false,
                Custom: [
                    {
                        Type: 0,
                        Position: "right"
                    }
                ]
            },
            {SplitCount: 3, IsShowLeftText: false},
            {SplitCount: 3, IsShowLeftText: false}
        ],

        //扩展图形
        ExtendChart: [
            //{ Name:'KLineTooltip' },  //手机端tooltip
        ]
    };

    return option;
};

DefaultData.GetMinuteDayMenu = function () {
    var data = [
        {Name: "1D", ID: 1},
        {Name: "2D", ID: 2},
        {Name: "3D", ID: 3},
        {Name: "4D", ID: 4},
        {Name: "5D", ID: 5}
    ];

    return data;
};

DefaultData.GetKLinePeriodMenu = function () {
    var data = [
        {Name: i18n.t('hj86'), ID: 3}, // 分时
        {Name: i18n.t('hj87'), ID: 0}, // 天
        {Name: i18n.t('hj88'), ID: 1}, // 周
        {Name: i18n.t('hj89'), ID: 2}, // 月
        {Name: i18n.t('hj90'), ID: 4}, // 1分
        {Name: i18n.t('hj91'), ID: 5}, // 5分
        {Name: i18n.t('hj92'), ID: 7} // 30分
    ];

    return data;
};

DefaultData.GetKLineRightMenu = function () {
    var data = [
        {Name: i18n.t('hj93'), ID: 0},
        {Name: i18n.t('hj94'), ID: 1},
        {Name: i18n.t('hj95'), ID: 2}
    ];

    return data;
};

export default {
    props: {
        hktype: {
            type: String,
            default: ''
        }
    },

    beforeDestroy() {
        let klineOption = DefaultData.GetKLineOption();
        let chartOption = DefaultData.GetMinuteOption();
        chartOption.IsAutoUpdate = false;
        klineOption.NetworkFilter = (data, callback) => {}
        chartOption.NetworkFilter = (data, callback) => {}
        clearTimeout(this.Chart.Timeout)
        clearTimeout(this.KLineChart.Timeout)
        this.Chart.IsAutoUpdate = false;
        this.KLineChart.IsAutoUpdate = false;
        if(this.Chart) {
            this.Chart.SetOption(chartOption);
        }
        if(this.KLineChart) {
            debugger;
            this.KLineChart.SetOption(klineOption);
        }
        this.Chart = null;
        this.KLineChart = null;
        console.log("shit")
        // 停止自动更新并清理图表数据
        // this.Chart && this.Chart.Clear();  // 假设 Clear 是清理图表的方法
        // this.KLineChart && this.KLineChart.Clear();

    },
    data() {
        return {
            tabsPositionNumArr: [],
            MinuteDayMenu: DefaultData.GetMinuteDayMenu(),
            MinuteDayIndex: 0,
            KLinePeriodMenu: DefaultData.GetKLinePeriodMenu(),
            KLinePeriodIndex: 1,
            KLineRightMenu: DefaultData.GetKLineRightMenu(),
            KLineRightIndex: 0,
            IsShowRightMenu: true,
            MinuteIndexMenu: DefaultData.GetMinuteIndexMenu(),
            KLineIndexMenu: DefaultData.GetKLineIndexMenu(),

            // Symbol:'000001_0.sh',
            // 上海 1.sh  深圳0.sz  北京0.bj

            Symbol: "", //HQChart内部编码美股加后缀.usa AAPL.usa


            Chart: null, //图形控件  分时图
            KLineChart: null, //图形控件  K线图

            VolChartHeight: 10,
            chartType: "kline",
            isShow: false
        };
    },
    created() {
        const {query} = this.$route;
        if (query.type === "qh") {
            const splited = query.code.split('_');
            if (query.code.includes('CFF_RE')) {
                this.Symbol = `${splited[splited.length - 1]}_220.CFF_RE`;
            } else {
                this.Symbol = `${splited[1]}.${splited[0]}`;
            }
        } else {
            if (query.if_zhishu === "0") {
                this.Symbol = `${query.code}_${query.sok}.${query.type}`;
            } else if ((query.code.indexOf('hk') > -1) && query.if_zhishu !== 0) {
                this.Symbol = `${query.if_zhishu}_${query.sok}.hk`;
            } else {
                this.Symbol = `${query.if_zhishu}_${query.sok}.${query.type}`;
            }
        }

        // this.Symbol = 'BRK_A106.usa'

        console.log('------?????', this.Symbol);
    },

    mounted() {
        this.offHeight = this.$refs["rightContent"].offsetHeight;
        this.OnSize();
        this.SetChartStyle();
        this.$nextTick(() => {
            this.CreateMinuteChart();
            this.CreateKLineChart();
        });
        let that = this;
        window.onresize = _.debounce(this.OnSize, 200);
        // 自适应K线图
        var elementResizeDetectorMaker = require("element-resize-detector");

        // 创建实例，无参数
        var erd = elementResizeDetectorMaker(); //使用默认选项（将使用基于对象的方法）。

        // 创建实例带参数
        // 使用基于超快速滚动的方法。
        // 这是推荐的策略。
        var erdUltraFast = elementResizeDetectorMaker({
            strategy: "scroll",
            callOnAdd: true, //callOnAdd选项，用于确定在添加侦听器时是否应调用它们。默认为true。
            //如果为true，则确保在添加侦听器后将对其进行调用。如果为false，则在添加侦听器时将不保证其
            //被调用（不会阻止其被调用）
            debug: true
        });
        //监听class为staticNextMain的元素 大小变化
        var self = this;
        //侦听元素的调整大小事件，并使用元素作为调整大小事件的参数来调用侦听器函数。传递给函数的选项将
        //覆盖实例选项
        erd.listenTo(this.$refs["rightContent"], function (
            element
        ) {
            var width = element.offsetWidth;
            var height = element.offsetHeight;
            self.tableHeight = height - 100; //将监听到的宽高进行赋值
            self.tableWidth = width - 20;
            that.offHeight = height;
            that.OnSize();
        });
    },

    methods: {
        OnSize() {
            var width = this.$refs.right.clientWidth;
            var rightTab = this.$refs.rightTab;
            var periodWrap = this.$refs.minute_periodWrap;
            var indexWrap = this.$refs.minute_indexWrap;
            var statementWrap = this.$refs.minute_statementWrap;
            // var chartHeight = window.innerHeight - rightTab.offsetHeight - periodWrap.offsetHeight - indexWrap.offsetHeight;
            var chartHeight = this.offHeight;

            var kline = this.$refs.kline;
            kline.style.width = width + "px";
            kline.style.height = chartHeight + "px";
            var kline2 = this.$refs.kline2;
            kline2.style.width = width + "px";
            kline2.style.height = chartHeight + "px";

            if (this.Chart) this.Chart.OnSize();
            if (this.KLineChart) this.KLineChart.OnSize();
        },

        changeRightContent(type) {
            this.KLinePeriodIndex = 0;
            this.chartType = type;
            this.$nextTick(() => {
                this.OnSize();
            });
        },

        SetChartStyle() {
            EastMoney.HQData.SetMinuteChartCoordinate();
            var blackStyle = HQChart.Chart.HQChartStyle.GetStyleConfig(
                HQChart.Chart.STYLE_TYPE_ID.WHITE_ID
            ); //读取黑色风格配置
            HQChart.Chart.JSChart.SetStyle(blackStyle);
        },

        CreateMinuteChart() {
            if (this.Chart) return;

            var option = DefaultData.GetMinuteOption();
            option.Symbol = this.Symbol;
            option.NetworkFilter = (data, callback) => {
                this.NetworkFilter(data, callback);
            }; //网络请求回调函数

            var chart = HQChart.Chart.JSChart.Init(this.$refs.kline);
            console.log("k线")
            console.log(chart)
            chart.SetOption(option);
            this.Chart = chart;
        },

        CreateKLineChart() {
            if (this.KLineChart) return;

            var option = DefaultData.GetKLineOption();
            option.Symbol = this.Symbol;
            option.NetworkFilter = (data, callback) => {
                this.NetworkFilter(data, callback);
            }; //网络请求回调函数

            var chart = HQChart.Chart.JSChart.Init(this.$refs.kline2);

            HQChart.Chart.JSChart.GetResource().FrameLogo.Text = null;
            chart.SetOption(option);
            this.KLineChart = chart;
        },

        ChangeSymbol(
            symbol //切换股票
        ) {
            var symbolUpper = symbol.toUpperCase();
            var isShowVolChart = EastMoney.HQData.IsShowVolChart(symbolUpper);
            var frame = this.Chart.JSChartContainer.Frame.SubFrame[1];
            if (isShowVolChart) {
                if (frame.Height <= 0) frame.Height = this.VolChartHeight;
            } else {
                if (frame.Height > 0) this.VolChartHeight = frame.Height;
                frame.Height = 0;
            }
            var period = this.KLineChart.JSChartContainer.Period;
            var isShowRightMenu = EastMoney.HQData.IsEnableRight(period, symbol); //是否显示复权菜单
            this.IsShowRightMenu = isShowRightMenu;

            this.Symbol = symbol;
            this.Chart.ChangeSymbol(this.Symbol);
            this.KLineChart.ChangeSymbol(this.Symbol);
        },

        OnClickMinuteDayMenu(
            index,
            item //分时图天数
        ) {
            this.MinuteDayIndex = index;
            this.Chart.ChangeDayCount(item.ID);
        },

        OnClickKLinePeriodMenu(
            index,
            item,
            type //K线周期
        ) {
            if (index != 0) {
                this.chartType = type;
                this.KLinePeriodIndex = index;
                this.KLineChart.ChangePeriod(item.ID);
            }
        },

        OnClickKLineRightMenu(
            index,
            item //K线复权
        ) {
            this.KLineRightIndex = index;
            this.KLineChart.ChangeRight(item.ID);
        },

        ChangeMinuteIndex(
            item //切换分时图指标
        ) {
            if (this.Chart) this.Chart.ChangeIndex(item.WindowIndex, item.ID);
        },

        ChangeKLineIndex(
            item //切换K线图指标
        ) {
            if (this.KLineChart)
                this.KLineChart.ChangeIndex(item.WindowIndex, item.ID);
        },

        NetworkFilter(
            data,
            callback //第3方数据替换接口
        ) {
            EastMoney.HQData.Log("[HQChartDemo::NetworkFilter] data", data);

            switch (data.Name) {
                //分时图数据对接
                case "MinuteChartContainer::RequestMinuteData":
                    EastMoney.HQData.NetworkFilter(data, callback);
                    break;
                case "MinuteChartContainer::RequestHistoryMinuteData":
                    EastMoney.HQData.NetworkFilter(data, callback);
                    break;

                case "KLineChartContainer::RequestHistoryData": //日线全量数据下载
                    EastMoney.HQData.NetworkFilter(data, callback);
                    break;
                case "KLineChartContainer::RequestRealtimeData": //日线实时数据更新
                    EastMoney.HQData.NetworkFilter(data, callback);
                    break;
                case "KLineChartContainer::RequestFlowCapitalData": //流通股本
                    EastMoney.HQData.NetworkFilter(data, callback);
                    break;
                case "KLineChartContainer::ReqeustHistoryMinuteData": //分钟全量数据下载
                    EastMoney.HQData.NetworkFilter(data, callback);
                    break;
                case "KLineChartContainer::RequestMinuteRealtimeData": //分钟增量数据更新
                    EastMoney.HQData.NetworkFilter(data, callback);
                    break;
            }
        },

        handleSelect(key, keyPath) {
            console.log(key, keyPath);
            this.ChangeSymbol(keyPath[1]);
        },

        handleOpen(key, keyPath) {
            console.log(key, keyPath);
        },

        handleClose(key, keyPath) {
            console.log(key, keyPath);
        }
    }
};
</script>
<style lang="less">
@animation-duration: 0.3s;

.box {
    width: 100%;
    height: 100%;
    // display: flex;
    position: relative;
    overflow: hidden;
    background: none;

    .left,
    .right {
        // position: absolute;
        top: 0;
    }

    .left {
        width: 240px;
        height: 100%;
        box-sizing: border-box;
        left: 0;
        // padding-top: 17px;
        overflow-x: auto;

        .el-menu {
            min-height: 100%;

            .el-submenu__title:hover {
                background-color: #363636 !important;
            }

            .el-menu-item:hover {
                background-color: #363636 !important;
            }
        }
    }

    .right {
        left: 240px;
        // width: calc(100% - 240px);
        width: 100%;
        height: 100%;
        @rightTabHeight: 40px;
        display: flex;
        flex-direction: column;

        .rightTab {
            height: @rightTabHeight;
            width: 100%;
            background: #191919;
            border-bottom: 1px solid #000;
            box-sizing: border-box;
            display: flex;
            align-items: center;
            justify-content: center;
            // flex-direction: column;

            > .btn {
                cursor: pointer;
                width: 100%;
                text-align: center;
                color: #000;

                &:first-child {
                    padding-right: 60px;
                    text-align: right;
                }

                &:last-child {
                    padding-left: 60px;
                    text-align: left;
                }

                &:hover,
                &.active {
                    color: rgb(2, 99, 226);
                }
            }
        }

        .rightContent {
            height: calc(100% - @rightTabHeight);
            width: 100%;

            .kline_periodWrap {
                display: flex;
                justify-content: space-between;
                background: #191919;

                .btnGroup:first-child {
                    width: 60%;
                }

                .btnGroup:last-child {
                    width: 100%;
                }
            }
        }

        .btnGroup {
            // border: 1px solid #242424;
            color: #000;
            display: flex;
            background: #fff;

            .btn {
                margin: 0 0.1rem;
                align-items: center;
                justify-content: center;
                // border-right: 1px solid #242424;
                color: #000;
                cursor: pointer;

                &:last-child {
                    border-right: none;
                }
            }

            .active {
                color: rgb(2, 99, 226);
                font-weight: 800;
                background: rgb(245, 245, 245);
            }
        }

        // .el-button-group{
        //   width: 100%;
        //   display: flex;

        //   .el-button{
        //     flex: 1;
        //   }
        // }

        #hqchart_minute {
            // height: 100%;
            background-color: #fff;
            height: 5rem;
            position: relative;
        }

        #hqchart_kline {
            // height: 100% !important;
            background-color: #fff;
            height: 5rem;
            position: relative;
        }

        .statementWrap {
            background: #191919;
            padding: 10px;
            font-size: 12px;
            color: #de432d;
            line-height: 20px;
            text-align: center;
        }
    }
}

// .schart-drawing {
//   height: 100% !important;
// }
.periodWrap {
    height: 0.7rem;
    // margin: 0.01rem 0 0.13rem 0;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #fff !important;
}

.btnGroup {
    height: 100%;

    .bt2 {
        height: 100% !important;
        box-shadow: none !important;

        img {
            width: 0.5rem; //dengwo xia
            height: 0.5rem;
        }
    }
}

.btn2 {
    width: 9.4%;
    display: flex;
    margin: 0 0.15rem;
    justify-content: center;
    align-items: center;
    border-radius: 0.15rem;

    img {
        width: 0.5rem;
        height: 0.5rem;
    }

    .active {
        color: rgb(2, 99, 226);
        font-weight: 800;
        background: rgb(245, 245, 245);
    }
}

canvas {
    height: 100% !important;
}

.hqchart {
    width: 100%;
    height: 7.5rem;
}
</style>
